﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AG.Data;

namespace AGUnitEditor.Windows
{
    public partial class AGCreateUnitWindow : Form
    {
        public AGUnit CreatedUnit { get; private set; }

        public AGCreateUnitWindow()
        {
            InitializeComponent();

            int maxUnitId = 0;
            for (int index = 0; index < AGUEContext.Current.Data.UnitList.Count; index++)
            {
                if (AGUEContext.Current.Data.UnitList[index].Id > maxUnitId)
                {
                    maxUnitId = AGUEContext.Current.Data.UnitList[index].Id;
                }
            }
            _ctlEditId.Text = maxUnitId.ToString();
            _ctlListCategory.DataSource = AGUEContext.Current.Data.UnitCategoryList;
        }

        private void _ctlBtnCreate_Click(object sender, EventArgs e)
        {
            AGModel selModel = _ctlBtnSelectModel.Tag as AGModel;
            if (selModel == null)
            {
                return;
            }
            AGUnitCategory category = _ctlListCategory.SelectedItem as AGUnitCategory;
            if (category == null)
            {
                return;
            }

            CreatedUnit = new AGUnit();
            CreatedUnit.Id = Convert.ToUInt16(_ctlEditId.Text);

            for (int index = 0; index < AGUEContext.Current.Data.UnitList.Count; index++)
            {
                if (AGUEContext.Current.Data.UnitList[index].Id == CreatedUnit.Id)
                {
                    MessageBox.Show("此编号已经存在，请重新输入!");
                    return;
                }
            }

            CreatedUnit.Caption = _ctlEditCaption.Text;
            CreatedUnit.CategoryId = category.Id;
            CreatedUnit.ModelId = selModel.Id;
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void _ctlBtnSelectModel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AGSelectModelWindow window = new AGSelectModelWindow(AGUEContext.Current.Data.ModelCategoryList,
                AGUEContext.Current.Data.ModelList);
            if (window.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _ctlBtnSelectModel.Text = window.SelectedModel.ToString();
                _ctlBtnSelectModel.Tag = window.SelectedModel;
                if (string.IsNullOrEmpty(_ctlEditCaption.Text))
                {
                    _ctlEditCaption.Text = window.SelectedModel.Caption;
                }
            }
        }
    }
}
